<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\Session;

class Login extends Controller
{
    /**
     * 执行登录
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function doLogin(Request $request)
    {
        //接收用户名和密码
        $data = $request->post();
        $username = $data['username'];
        $password = $data['password'];
        //验证
      
       
        $data = Db::name('admin')->where(['name'=>$username])->find();
        // var_dump($data);die;


        if (!$data) {
            $this->error('用户名不存在！');
            exit;
        }
        //验证密码
        if ($data['pass'] != $password) {
            $this->error('密码不正确');
            exit;
        }
        //把用户信息添加到session

        // Session::set('user',$data,'think');
    
        //根据用户id获取对应的权限信息

        // $sql = 'select p.controller,p.funcname from bk_power p, bk_role r,bk_rolepower rp, bk_admin a, bk_userrole ur  where a.id =ur.uid and ur.roleid = r.id and r.id = rp.roleid and rp.powerid = p.id'
        $list = DB::name('power')->field('controller,funcname')->where('id in'.Db::name('rolepower')->field('powerid')->where("roleid in ".Db::name('userrole')->field('roleid')->where(array('uid'=>array('eq',$data['id'])))->buildSql())->buildSql())->select();
        //控制器名转换为大写
        foreach ($list as $key => $val) {
            $list[$key]['controller'] = ucfirst($val['controller']);
        }
        $powerlist = array();
        $powerlist['message'] = array($data);
        $powerlist['Index'] = array('index');

        //遍历重新拼装
        foreach($list as $v){
            $powerlist[$v['controller']][] = $v['funcname'];
            //把修改和执行修改 添加和执行添加 拼装到一起
            if($v['funcname']=="edit"){
                $powerlist[$v['controller']][]="doEdit";
                
            }
            if($v['funcname']=="add"){
                $powerlist[$v['controller']][]="doAdd";
            }
        }  
        // var_dump($powerlist);exit;         

        //将权限信息放置到session中
        Session::set('admin',$powerlist,'think');
    

        //跳转到首页
        $this->redirect('Index/main');
    }  
}
